import React, {useState, useEffect, useCallback} from 'react';
import {Form} from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {Modal, message, Select} from 'antd';
import {getFieldValueApi, addPreference, checkForDup} from '~/service/performance';
import {TARGET_TYPE, PAGER} from '~/utils/const';
import useStore from './FormStore';
import popUpContainer from './popupFix';

const {Option} = Select;
const {confirm} = Modal;

/**
 * @Creator: andycao
 * @Date: 2020/05/25
 * 核心页面配置 添加路径
 */
// eslint-disable-next-line max-lines-per-function
function AddPath(props) {
    const {
        form: {
            getFieldDecorator,
            validateFields,
            resetFields,
        },
        visible, handleOk, pageId
    } = props;
    const targetList = [...TARGET_TYPE.keys()];
    const [selectedTarget, setSelectedTarget] = useState([]);

    const [state, dispatch] = useStore({});
    const {business, businessList, project, projectList, path, pathList} = state;
    const [pathPage, setPathPage] = useState(1);
    const [hasMore, setHasMore] = useState(true);
    async function getBusinessList(type, params) {
        const res = await getFieldValueApi(params);
        if (res === null) {
            return;
        }
        if (res.code !== 0) {
            message.error(res.msg);
            return;
        }
        const list = res.data.values;
        const {pager} = res;

        switch (type) {
            case 'business':
                dispatch({
                    type: 'changeBusinessList',
                    data: list
                });
                break;
            case 'project':
                dispatch({
                    type: 'changeProjectList',
                    data: list
                });
                break;
            case 'path':
                dispatch({
                    type: 'changePathList',
                    data: list
                });
                break;
            case 'appendPath':
                // 是否有更多的path
                setHasMore(pathList.length + list.length < pager.count);
                dispatch({
                    type: 'appendPath',
                    data: list
                });
                break;
            default:
                break;
        }
    }

    function closeModal() {
        resetFields();
        dispatch({
            type: 'reset'
        });
        setSelectedTarget([]);
        handleOk();
    }

    function handleSubmit(e) {
        e.preventDefault();
        validateFields(error => {
            if (!error) {
                const param = {
                    pageId,
                    bizTypeName: business,
                    bizName: project,
                    paths: path,
                    targetTypes: selectedTarget
                };

                duplicateCheck(param).then(check => {
                    if (check) {
                        confirm({
                            title: '新加路径已存在，已存在路径仍然保持，是否继续添加?',
                            onOk() {
                                doAddPreference(param);
                            },
                        });
                    }
                    else {
                        doAddPreference(param);
                    }
                });
            }
        });
    }

    function doAddPreference(param) {
        addPreference(param).then(res => {
            if (res.code === 0) {
                closeModal();
                handleOk(true);
            }
            else {
                message.error(res.msg);
            }
        });
    }

    async function duplicateCheck(param) {
        const res = await checkForDup(param);
        if (res.code === 0) {
            return res.data;
        }
        message.error(res.msg);
        return false;
    }

    // 修改业务线
    const onChangeBusiness = useCallback(business => {
        dispatch({
            type: 'changeBusiness',
            data: {
                business
            }
        });
        resetFields(['project', 'paths']);
        setPathPage(1);
        getBusinessList('project', {
            field: 'biz_name',
            bizTypeName: business
        });
    }, []);

    // 应用
    const onChangeProject = useCallback(project => {
        dispatch({
            type: 'changeProject',
            data: {
                project
            }
        });
        resetFields(['paths']);
        setPathPage(1);
        getBusinessList('path', {
            field: 'path',
            bizTypeName: business,
            bizName: project,
            pager: {
                ...PAGER,
                pageNum: 1
            }
        });
    }, []);

    // path
    const onChangePath = useCallback(path => {
        dispatch({
            type: 'changePath',
            data: {
                path
            }
        });
    }, []);

    function searchPath(keyword) {
        setPathPage(1);
        getBusinessList('appendPath', {
            field: 'path',
            bizTypeName: business,
            bizName: project,
            keyword,
            pager: {
                ...PAGER,
                pageNum: 1
            }
        });
    }

    function scrollPath(e) {
        e.persist();
        const {target} = e;
        if (target.scrollTop + target.offsetHeight === target.scrollHeight && hasMore) {
            const nextScrollPage = pathPage + 1;
            setPathPage(nextScrollPage);
            getBusinessList('appendPath', {
                field: 'path',
                bizTypeName: business,
                bizName: project,
                pager: {
                    ...PAGER,
                    pageNum: nextScrollPage
                }
            });
        }
    }

    function onChangeTargetType(list) {
        setSelectedTarget(list);
    }

    useEffect(() => {
        getBusinessList('business', {
            field: 'biz_type_name'
        });
    }, []);

    return (
        <Modal
            title="应用内指标"
            visible={visible}
            onOk={handleSubmit}
            onCancel={closeModal}
            style={{minWidth: '50vw'}}
        >
            <Form onSubmit={handleSubmit} labelCol={{span: 6}} wrapperCol={{span: 18}}>
                <Form.Item label="业务线">
                    {
                        getFieldDecorator('business', {
                            rules: [
                                {
                                    required: true,
                                    message: '请输入业务线',
                                },
                            ],
                        })(
                            <Select
                                placeholder="请选择"
                                onChange={onChangeBusiness}
                                getPopupContainer={popUpContainer}
                            >
                                {
                                    businessList.map((item, index) => (
                                        <Option key={item} value={item} title={item}>
                                            {item}
                                        </Option>
                                    ))
                                }
                            </Select>
                        )
                    }
                </Form.Item>
                <Form.Item label="应用">
                    {
                        getFieldDecorator('project', {
                            rules: [
                                {
                                    required: true,
                                    message: '请输入应用',
                                },
                            ],
                        })(
                            <Select
                                showSearch
                                placeholder="请选择"
                                onChange={onChangeProject}
                                getPopupContainer={popUpContainer}
                            >
                                {
                                    projectList.map((item, index) => (
                                        <Option key={item} value={item} title={item}>
                                            {item}
                                        </Option>
                                    ))
                                }
                            </Select>
                        )
                    }
                </Form.Item>
                <Form.Item label="路径">
                    {
                        getFieldDecorator('paths', {
                            rules: [
                                {
                                    required: true,
                                    message: '请输入路经',
                                },
                            ],
                        })(
                            <Select
                                placeholder="请选择"
                                onChange={onChangePath}
                                onPopupScroll={scrollPath}
                                onSearch={searchPath}
                                mode="multiple"
                                getPopupContainer={popUpContainer}
                            >
                                {
                                    pathList.map(item => (
                                        <Option key={item} value={item} title={item}>
                                            {item}
                                        </Option>
                                    ))
                                }
                            </Select>
                        )
                    }
                </Form.Item>
                <Form.Item label="指标">
                    {
                        getFieldDecorator('targets', {
                            rules: [
                                {
                                    required: true,
                                    message: '请输入指标',
                                },
                            ],
                        })(
                            <Select
                                placeholder="请选择"
                                onChange={onChangeTargetType}
                                mode="multiple"
                                getPopupContainer={popUpContainer}
                            >
                                {
                                    targetList.map(entry => (
                                        <Option key={entry} value={entry} title={entry}>
                                            {TARGET_TYPE.get(entry)}
                                        </Option>
                                    ))
                                }
                            </Select>
                        )
                    }
                </Form.Item>
            </Form>
        </Modal>
    );
}

export default Form.create({name: 'addPath'})(AddPath);
